<?php

namespace Helpers;

use Phalcon\Di;
use Phalcon\Cache\Frontend\Data as FrontendData;
use Phalcon\Cache\Backend\Memcache;

class Cache{

    /**
     * @var Memcache
     */
    static $cache = false;
    static $error = false;
    private static $prefix = null;

    /**
     * 获取cache实例，异常则返回false
     *
     * @return Memcache
     *
     * create by ck 20170706
     */
    private static function connect()
    {
        if(!self::$cache && !self::$error){
            try {
                $config                 = Di::getDefault()->get('config')->get('memcache')->toArray();
                $config['lifetime']     = eval("return {$config['lifetime']};");              //计算生存周期
                $frontCache             = new FrontendData(['lifetime' => $config['lifetime']]);
                $config['statsKey']     = '_PHCM'; unset($config['lifetime']);
                self::$cache            = new Memcache($frontCache, $config);
                self::$prefix           = $config['prefix'];
                @self::$cache->start(1);
            }
            catch(\Exception $e){
                self::$cache = false;
                self::$error = $e->getMessage();
                return self::$cache;
            }
        }
        return self::$cache;
    }

    public static function exists($keyName = null, $lifetime = null)
    {
        self::connect();
        return !self::$cache ? false : self::$cache->exists($keyName, $lifetime);
    }

    public static function get($keyName = null, $lifetime = null)
    {
        self::connect();
        return !self::$cache ? false : self::$cache->get($keyName, $lifetime);
    }

    public static function save($keyName = null, $content = null, $lifetime = null, $stopBuffer = true)
    {
        self::connect();
        return !self::$cache ? false : self::$cache->save($keyName, $content, $lifetime, $stopBuffer);
    }

    public static function delete($keyName)
    {
        self::connect();
        return !self::$cache ?: !self::$cache ? false : self::$cache->delete($keyName);
    }

    public static function flush()
    {
        self::connect();
        return !self::$cache ? false : self::$cache->flush();
    }

    public static function queryKeys($prefix = null)
    {
        self::connect();
        return !self::$cache ? false : self::$cache->queryKeys(self::$prefix ? self::$prefix . $prefix : $prefix);
    }

}